package com.operate.config;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.operate.utils.JedisUtil3;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: ZeckZheng
 * @time: 2023/11/1 21:07
 */
@Slf4j
@Service
public class HttpConfig {

    @Value("${user.access.token}")
    private String access_token;

    @Value("${user.refresh.token}")
    private String refresh_token;

    @Value("${user.app.id}")
    private String app_id;

    @Value("${user.app.secret}")
    private String app_secret;

    @Value("${user.app.access.token.url}")
    private String app_access_token_url;

    @Value("${user.user.access.token.url}")
    private String user_access_token_url;


    public String GET(String url) {
        String auth = "Bearer " + access_token;
        String result = cn.hutool.http.HttpUtil.createGet(url)
                //这个请求头.header是自己项目需要加的，可以省略
                .header("Authorization", auth).execute()
                //返回参数格式utf-8
                .charset("utf-8").body();
        //99991668
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        if (!"0".equals(code)) {
            log.error(result);
        }

        return result;
    }

    public String POST(String url, String param) {
        String auth = "Bearer " + access_token;
        String result = cn.hutool.http.HttpUtil.createPost(url)
                //这个请求头.header是自己项目需要加的，可以省略
                .header("Content-Type", "application/json")
                //这两个请求头是项目需要加的，可以省略
                .header("Authorization", auth)
                //传输参数
                .body(param).execute().body();
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        if (!"0".equals(code)) {
            log.error(result);
        }

        return result;
    }

    public void clearData(String queryUrl, String delUrl) {
        //查询
        String result = this.GET(queryUrl);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");

        if ("0".equals(code)) {
            JSONObject data = jsonObject.getJSONObject("data");
            Integer total = data.getInteger("total");
            if (total > 0) {
                List<String> del = new ArrayList<>();
                JSONArray items = data.getJSONArray("items");
                for (Object item : items) {
                    JSONObject recordInfo = (JSONObject) item;
                    String record_id = recordInfo.getString("record_id");
                    del.add(record_id);
                }
                Map<String, List> delParam = new HashMap<>();
                delParam.put("records", del);
                //删除
                String delResult = this.POST(delUrl, JSONObject.toJSONString(delParam));
                //log.info("删除结果: " + delResult);
            }
        }
    }

    public void handRefreshToken(String token) {
        refresh_token = token;
        refreshAppToken();
    }


    @Scheduled(cron = "${auto.refresh.token.cron}")
    public void autoRefreshToken() {
        refreshAppToken();
    }


    public void init() {
        Jedis jedis = JedisUtil3.getJedis();

        String redis_access_token = jedis.get("access_token");
        String redis_refresh_token = jedis.get("refresh_token");
        if (StringUtils.hasText(redis_access_token)) {
            access_token = redis_access_token;
            refresh_token = redis_refresh_token;
        }

        JedisUtil3.closeJedis(jedis);
    }

    @PreDestroy
    public void destroy() {
        log.info("access_token: {}", access_token);
        log.info("refresh_token: {}", refresh_token);
    }


    public boolean refreshAppToken() {

        boolean refresh_token_result = false;

        Map<String, String> appTokenParam = new HashMap<>();
        appTokenParam.put("app_id", app_id);
        appTokenParam.put("app_secret", app_secret);
        String result = cn.hutool.http.HttpUtil.createPost(app_access_token_url)
                //这个请求头.header是自己项目需要加的，可以省略
                .header("Content-Type", "application/json")
                //这两个请求头是项目需要加的，可以省略
                //传输参数
                .body(JSONObject.toJSONString(appTokenParam)).execute().body();

        JSONObject jsonObject = JSONObject.parseObject(result);
        if ("0".equals(jsonObject.getString("code"))) {
            String app_access_token = jsonObject.getString("app_access_token");
            log.info("app_access_token: {}", app_access_token);
            refresh_token_result = refreshUserToken(app_access_token);
        }
        return refresh_token_result;
    }

    public boolean refreshUserToken(String app_access_token) {
        boolean refresh_token_result = false;
        Map<String, String> param = new HashMap<>();
        param.put("grant_type", "refresh_token");
        param.put("refresh_token", refresh_token);
        String auth = "Bearer " + app_access_token;
        String result = cn.hutool.http.HttpUtil.createPost(user_access_token_url)
                //这个请求头.header是自己项目需要加的，可以省略
                .header("Content-Type", "application/json")
                //这两个请求头是项目需要加的，可以省略
                .header("Authorization", auth)
                //传输参数
                .body(JSONObject.toJSONString(param)).execute().body();

        JSONObject jsonObject = JSONObject.parseObject(result);

        String code = jsonObject.getString("code");
        if ("0".equals(code)) {
            JSONObject data = jsonObject.getJSONObject("data");
            access_token = data.getString("access_token");
            refresh_token = data.getString("refresh_token");
            log.info("access_token: {}", access_token);
            log.info("refresh_token: {}", refresh_token);
            Jedis jedis = JedisUtil3.getJedis();
            jedis.set("access_token", access_token);
            jedis.set("refresh_token", refresh_token);
            jedis.expire(access_token,1800);
            jedis.expire(refresh_token,1800);
            JedisUtil3.closeJedis(jedis);
            return true;

        }
        log.error(result);
        return refresh_token_result;
    }

    public String getRefreshToken() {
        return refresh_token;
    }

    public String getAccessToken() {
        return access_token;
    }


}
